package fr.toto.files;

import java.awt.Desktop;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.kokotchy.betaSeriesAPI.model.Episode;

import fr.toto.constantes.Constantes;
import fr.toto.triseries.Regex;
import fr.toto.triseries.Reglages;

public class AccesFile implements Constantes {

	public static Path Find(Episode ep) {
		String glob = Regex.getEpisodeFile(ep).getFileName().toString()
				+ Reglages.getExtsGlob();

		for (String s : Reglages.GetDirsToFiles()) {
			Path p = Paths.get(s, Regex.getEpisodeFile(ep).getParent()
					.toString());
			if (Files.exists(p)) {
				DirectoryStream<Path> stream = null;
				try {
					stream = Files.newDirectoryStream(p, glob);
					if (stream != null)
						for (Path path : stream) {
							if (path != null)
								return path;
						}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (stream != null)
							stream.close();
					} catch (IOException e) {
						//TODO
						e.printStackTrace();
					}
				}
			}
		}
		return null;

	}

	public static void Open(Path p) {
		if (DEBUG)
			System.out.println(p);
		if (Desktop.isDesktopSupported()) {

			Desktop desktop = Desktop.getDesktop();

			if (desktop.isSupported(Desktop.Action.OPEN)) {
				try {
					desktop.open(p.toFile());
				} catch (IOException ex) {
					//TODO
					ex.printStackTrace();
				}
			}
		}

	}

}
